<route lang="json5" type="page">
{
	style: {
		navigationStyle: 'default',
		navigationBarBackgroundColor: '#FFFFFF',
		navigationBarTextStyle: 'black',
		backgroundColor: '#FFFFFF',
		navigationBarTitleText: '完善信息',
	},
}
</route>
<template>
	<block>
		<uni-forms ref="formRef" :rules="rules" :modelValue="formData">
			<view class="page-personal px-8 box-border pt-[100rpx] pb-4">
				<text class="text-[#303030] text-[50rpx] w-[100%]" style="float: left; font-weight: bold"
					>完善信息</text
				>
				<text class="text-[#303030] text-[24rpx]">为您推荐更符合您的阅读书籍，请完善以下资料</text>
				<view class="w-full box-border mb-3 mt-4">
					<view class="px-[32rpx] rounded-[63rpx] px-8 py-3" style="background-color: #f6f7f9">
						<uni-forms-item name="user_name" label="姓名">
							<view class="w-full flex h-full justify-between items-center box-border">
								<input
									class="flex-1"
									placeholder="请填写姓名"
									:maxlength="10"
									v-model="formData.user_name"
									@input="setValue('user_name', formData.user_name)"
								/>
								<image class="w-[34rpx] h-[34rpx]" :src="baseImg + '/personal-name.png'"></image>
							</view>
						</uni-forms-item>
					</view>
				</view>
				<view class="w-full box-border mb-3">
					<view class="px-[32rpx] rounded-[63rpx] px-8 py-3" style="background-color: #f6f7f9">
						<uni-forms-item name="city_id" label="地区">
							<view
								@tap="openModal('city_id', '选择地区')"
								class="w-full flex h-full justify-between items-center box-border"
							>
								<view
									class="flex-1"
									:style="{ color: formData.city_name ? '#303030' : '#C6C6C6' }"
									>{{ formData.city_name || '请选择地区' }}</view
								>
								<image class="w-[50rpx] h-[50rpx]" :src="baseImg + '/my-link.png'"></image>
							</view>
						</uni-forms-item>
					</view>
				</view>
				<view class="w-full box-border mb-3">
					<view class="px-[32rpx] rounded-[63rpx] px-8 py-3" style="background-color: #f6f7f9">
						<uni-forms-item name="county_id" label="区县">
							<view
								@tap="openModal('county_id', '选择区县')"
								class="w-full flex h-full justify-between items-center box-border"
							>
								<view
									class="flex-1"
									:style="{ color: formData.county_name ? '#303030' : '#C6C6C6' }"
									>{{ formData.county_name || '请选择区县' }}</view
								>
								<image class="w-[50rpx] h-[50rpx]" :src="baseImg + '/my/my-link.png'"></image>
							</view>
						</uni-forms-item>
					</view>
				</view>
				<view class="w-full box-border mb-3">
					<view class="px-[32rpx] rounded-[63rpx] px-8 py-3" style="background-color: #f6f7f9">
						<uni-forms-item name="school_id" label="学校">
							<view
								@tap="openModal('school_id', '选择学校')"
								class="w-full flex h-full justify-between items-center box-border"
							>
								<view
									class="flex-1"
									:style="{ color: formData.school_name ? '#303030' : '#C6C6C6' }"
									>{{ formData.school_name || '请选择学校' }}</view
								>
								<image class="w-[50rpx] h-[50rpx]" :src="baseImg + '/my-link.png'"></image>
							</view>
						</uni-forms-item>
					</view>
				</view>
				<view class="w-full box-border mb-3">
					<view class="px-[32rpx] rounded-[63rpx] px-8 py-3" style="background-color: #f6f7f9">
						<uni-forms-item name="grade" label="年级">
							<view
								@tap="openModal('grade', '选择年级')"
								class="w-full flex h-full justify-between items-center box-border"
							>
								<view
									class="flex-1"
									:style="{ color: formData.grade_name ? '#303030' : '#C6C6C6' }"
									>{{ formData.grade_name || '请选任教年级，可多选，9月1日将自动升年级' }}</view
								>
								<image class="w-[50rpx] h-[50rpx]" :src="baseImg + '/my/my-link.png'"></image>
							</view>
						</uni-forms-item>
					</view>
				</view>
				<!-- <view class="w-full box-border mb-3">
					<view class="px-[32rpx] rounded-[63rpx] px-8 py-3" style="background-color: #f6f7f9">
						<uni-forms-item name="class_id" label="班级">
							<view
								@tap="openModal('class_id', '选择班级')"
								class="w-full flex h-full justify-between items-center box-border"
							>
								<view
									class="flex-1"
									:style="{ color: formData.class_name ? '#303030' : '#C6C6C6' }"
									>{{ formData.class_name || '请选择班级' }}</view
								>
								<image class="w-[50rpx] h-[50rpx]" :src="baseImg + '/my-link.png'"></image>
							</view>
						</uni-forms-item>
					</view>
				</view> -->
				<view class="w-full justify-center items-center flex mt-8 box-border">
					<view class="w-[430rpx] relative h-[105rpx]">
						<image
							class="w-full h-full absolute left-[50%] -translate-x-[50%] top-0 z-1"
							:src="baseImg + '/personal-success.png'"
						></image>
						<view
							@tap="submit"
							class="w-full h-full flex justify-center items-center absolute text-[#F4F7F4] text-[40rpx] left-[50%] -translate-x-[50%] top-0 z-2"
							>完 成</view
						>
					</view>
				</view>
			</view>
		</uni-forms>

		<uni-popup ref="popup" :mask-click="false" type="bottom" background-color="transparent">
			<view class="w-full h-[824rpx] px-6 py-4 box-border">
				<view
					class="w-full bg-white h-full rounded-[30rpx] py-6 box-border flex flex-col justify-center"
				>
					<view class="w-full h-[53rpx] flex justify-between items-center px-6 box-border">
						<image
							@tap="closeModal"
							:src="baseImg + '/close-btn.png'"
							class="w-[44rpx] h-[44rpx]"
						></image>
						<text class="text-[#303030] text-[44rpx]">{{ modalInfo.title }}</text>
						<view
							class="text-[#fff] text-[29rpx] rounded-[29rpx] h-[53rpx] flex px-4 justify-center items-center"
							style="background: #2ba5e0"
							@tap="confirm"
							>确认</view
						>
					</view>
					<view class="w-full pt-6 box-border" style="height: calc(100% - 53rpx)">
						<view class="h-full flex justify-between py-2 box-border">
							<scroll-view scroll-y class="w-full h-full">
								<view :class="[modalInfo.type === 'grade' ? 'grid grid-cols-3 gap-y-2' : '']">
									<view
										v-for="item in modalList"
										:key="item.id"
										@tap="setItem(item.id, item.name)"
										class="w-full flex justify-center items-center mb-2 last:mb-0"
									>
										<view
											class="max-w-full px-[38rpx] h-[54rpx] box-border flex justify-center items-center rounded-[27rpx] text-[#303030] text-[29rpx]"
											:style="{
												background:
													(modalInfo.id == item.id && modalInfo.type !== 'grade') ||
													(modalInfo.type === 'grade' &&
														modalInfo.id &&
														modalInfo.id.includes(item.id))
														? '#44C651'
														: '',
												color:
													(modalInfo.id == item.id && modalInfo.type !== 'grade') ||
													(modalInfo.type === 'grade' &&
														modalInfo.id &&
														modalInfo.id.includes(item.id))
														? '#fff'
														: '#303030',
											}"
											><text class="truncate">{{ item.name }}</text></view
										>
									</view>
								</view>
							</scroll-view>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</block>
</template>

<script lang="ts" setup>
import { getCityCountryList, getSchoolList, getClassList, getGradeList } from '@/service/common';
import { addTeacherInfo, getDefaultUserInfo } from '@/service/user';
import { useUserStore } from '@/store';
import { storeToRefs } from 'pinia';
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

const baseImg = ref(import.meta.env.VITE_STATIC_IMAGE);
const formRef = ref(null);
const popup = ref(null);
const cityList = ref([]);
const countyList = ref([]);
const gradeList = ref([]);
const schoolList = ref([]);
const classList = ref([]);
const modalList = ref([]);
const modalInfo = ref({
	type: '',
	title: '',
	id: null,
	name: '',
});
const formData = ref({
	user_name: '',
	city_name: '',
	county_name: '',
	school_name: null,
	grade_name: null,
	class_name: null,
	city_id: null,
	county_id: null,
	school_id: null,
	grade: null,
	// class_id: null,
});
const rules = ref({
	user_name: {
		rules: [
			{
				required: true,
				errorMessage: '姓名不能为空',
			},
		],
	},
	city_id: {
		rules: [
			{
				required: true,
				errorMessage: '地区不能为空',
			},
		],
	},
	county_id: {
		rules: [
			{
				required: true,
				errorMessage: '区县不能为空',
			},
		],
	},
	school_id: {
		rules: [
			{
				required: true,
				errorMessage: '学校不能为空',
			},
		],
	},
	grade: {
		rules: [
			{
				required: true,
				errorMessage: '年级不能为空',
			},
		],
	},
});

onShow(() => {
	// 获取地区数据
	getCityCountry();
});

const getGrade = async (sid: number) => {
	try {
		const res = await getGradeList(sid);
		if (res.status_code === 200 && res.data?.length) {
			gradeList.value = res.data;
		} else {
			gradeList.value = [];
		}
	} catch (error) {
		gradeList.value = [];
	}
};

const getCityCountry = async (id?: number) => {
	try {
		const res = await getCityCountryList(id);
		if (res.status_code === 200 && res.data?.length) {
			if (id) {
				countyList.value = res.data;
			} else {
				cityList.value = res.data;
			}
		} else if (id) {
			countyList.value = [];
			resetList('county_id');
		} else {
			cityList.value = [];
			resetList('city_id');
		}
	} catch (error) {
		if (id) {
			countyList.value = [];
			resetList('county_id');
		} else {
			cityList.value = [];
			resetList('city_id');
		}
	}
};

const getSchool = async (id?: number) => {
	try {
		const res = await getSchoolList(id);
		if (res.status_code === 200 && res.data?.length) {
			schoolList.value = res.data;
		} else {
			schoolList.value = [];
			if (id) {
				resetList('school_id');
			}
		}
	} catch (error) {
		schoolList.value = [];
		if (id) {
			resetList('school_id');
		}
	}
};

const getClass = async (id?: number) => {
	try {
		const res = await getClassList(id);
		if (res.status_code === 200 && res.data?.length) {
			classList.value = res.data.map(item => {
				return {
					id: item.id,
					name: item.class_name,
				};
			});
		} else {
			classList.value = [];
		}
	} catch (error) {
		classList.value = [];
	}
};

const resetList = type => {
	if (type === 'city_id') {
		countyList.value = [];
		schoolList.value = [];
		classList.value = [];
	}
	if (type === 'county_id') {
		schoolList.value = [];
		classList.value = [];
	}
	if (type === 'school_id') {
		classList.value = [];
	}
};

const setValue = (name, value) => {
	formRef.value?.setValue(name, value);
};

const openModal = (type?, title?) => {
	modalInfo.value.type = type;
	modalInfo.value.title = title;
	let id = '';
	let name = '';
	let list = [];
	if (type === 'grade') {
		list = gradeList.value;
		id = formData.value.grade;
		name = formData.value.grade_name;
	}
	if (type === 'city_id') {
		list = cityList.value;
		id = formData.value.city_id;
		name = formData.value.city_name;
	}
	if (type === 'county_id') {
		if (!formData.value.city_id) {
			uni.showToast({
				icon: 'none',
				title: '请先选择地区',
			});
			return;
		}
		id = formData.value.county_id;
		name = formData.value.county_name;
		list = countyList.value;
	}
	if (type === 'school_id') {
		if (!formData.value.county_id) {
			uni.showToast({
				icon: 'none',
				title: '请先选择区县',
			});
			return;
		}
		id = formData.value.school_id;
		name = formData.value.school_name;
		list = schoolList.value;
	}
	// if (type === 'class_id') {
	// 	if (!formData.value.school_id) {
	// 		uni.showToast({
	// 			icon: 'none',
	// 			title: '请先选择学校',
	// 		});
	// 		return;
	// 	}
	// 	id = formData.value.class_id;
	// 	name = formData.value.class_name;
	// 	list = classList.value;
	// }
	modalList.value = list;
	modalInfo.value.id = id;
	modalInfo.value.name = name;
	popup.value?.open();
};

const closeModal = () => {
	modalInfo.value = {
		type: '',
		title: '',
		id: '',
		name: '',
	};
	popup.value?.close();
};

const confirm = () => {
	const { type } = modalInfo.value;
	if (!modalInfo.value.id) {
		uni.showToast({
			icon: 'none',
			title: modalInfo.value.title,
		});
		return;
	}
	formData.value[type] = modalInfo.value.id;
	if (type === 'city_id') {
		formData.value.city_name = modalInfo.value.name;
		formData.value.county_name = null;
		formData.value.school_name = null;
		formData.value.grade_name = null;
		formData.value.class_name = null;
		formData.value.county_id = null;
		formData.value.school_id = null;
		formData.value.grade = null;
		// formData.value.class_id = null;
		getCityCountry(modalInfo.value.id);
	}
	if (type === 'county_id') {
		formData.value.county_name = modalInfo.value.name;
		formData.value.school_name = null;
		formData.value.grade_name = null;
		formData.value.class_name = null;
		formData.value.school_id = null;
		formData.value.grade = null;
		// formData.value.class_id = null;
		getSchool(modalInfo.value.id);
	}
	if (type === 'school_id') {
		formData.value.school_name = modalInfo.value.name;
		formData.value.grade_name = null;
		formData.value.class_name = null;
		formData.value.grade = null;
		// formData.value.class_id = null;
		getClass(modalInfo.value.id);
		// 获取年级
		getGrade(modalInfo.value.id);
	}
	// if (type === 'class_id') {
	// 	formData.value.class_name = modalInfo.value.name;
	// }
	if (type === 'grade') {
		formData.value.grade_name = modalInfo.value.name;
	}
	closeModal();
};

const setItem = (id, name) => {
	let newName = name;
	if (modalInfo.value.type === 'grade') {
		let arr = modalInfo.value.id || [];
		if (arr.includes(id)) {
			arr = arr.filter(item => item !== id);
		} else {
			arr.push(id);
		}
		newName = gradeList.value
			.filter(item => arr.includes(item.id))
			.map(item => item.name)
			.join(',');
		modalInfo.value.id = arr;
	} else {
		modalInfo.value.id = id;
	}
	modalInfo.value.name = name;
};

const getUserInfo = async () => {
	try {
		const res = await getDefaultUserInfo();

		if (res.status_code === 200 && res.data) {
			userStore.setUserInfo({ ...userStore.userInfo, ...res.data });
		} else {
			console.log('setUserInfo error');
		}
	} catch (error) {
		console.log('setUserInfo error');
	}
};

const submit = () => {
	uni.showLoading({ title: '保存中...' });
	formRef.value
		?.validate()
		.then(async res => {
			try {
				const data = await addTeacherInfo({ ...res, grade: res.grade.join(',') });
				uni.hideLoading();
				if (data.status_code === 200) {
					uni.showToast({
						icon: 'none',
						title: '保存成功',
					});
					getUserInfo();
					uni.switchTab({
						url: '/pages/index/index',
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: data.message,
					});
				}
			} catch (error) {
				uni.showToast({
					icon: 'none',
					title: '保存失败,请重试',
				});
				uni.hideLoading();
			}
		})
		.catch(err => {
			uni.hideLoading();
		});
};
</script>
<script lang="ts">
export default {
	options: { styleIsolation: 'shared' },
};
</script>

<style lang="scss">
page {
	background: #fff;
}
</style>
<style lang="scss" scoped>
:deep(.uni-forms-item) {
	margin-bottom: 0;
}
</style>
